/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.entity.StatusOrder;
import model.entity.Restaurant;
import model.entity.PaymentMethod;
import model.entity.Customer;
import model.entity.OrderDetail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.entity.Orders;

/**
 *
 * @author lnngu_000
 */
public class OrdersJpaController implements Serializable {

    public OrdersJpaController(EntityManagerFactory emf) {
        
        this.emf = emf;
    }
    
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Orders orders) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (orders.getOrderDetailCollection() == null) {
            orders.setOrderDetailCollection(new ArrayList<OrderDetail>());
        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            StatusOrder statusOrderId = orders.getStatusOrderId();
            if (statusOrderId != null) {
                statusOrderId = em.getReference(statusOrderId.getClass(), statusOrderId.getStatusOrderId());
                orders.setStatusOrderId(statusOrderId);
            }
            Restaurant restaurantId = orders.getRestaurantId();
            if (restaurantId != null) {
                restaurantId = em.getReference(restaurantId.getClass(), restaurantId.getRestaurantId());
                orders.setRestaurantId(restaurantId);
            }
            PaymentMethod paymentMethodId = orders.getPaymentMethodId();
            if (paymentMethodId != null) {
                paymentMethodId = em.getReference(paymentMethodId.getClass(), paymentMethodId.getPaymentMethodId());
                orders.setPaymentMethodId(paymentMethodId);
            }
            Customer customerId = orders.getCustomerId();
            if (customerId != null) {
                customerId = em.getReference(customerId.getClass(), customerId.getCustomerId());
                orders.setCustomerId(customerId);
            }
            Collection<OrderDetail> attachedOrderDetailCollection = new ArrayList<OrderDetail>();
            for (OrderDetail orderDetailCollectionOrderDetailToAttach : orders.getOrderDetailCollection()) {
                orderDetailCollectionOrderDetailToAttach = em.getReference(orderDetailCollectionOrderDetailToAttach.getClass(), orderDetailCollectionOrderDetailToAttach.getOrderDetailId());
                attachedOrderDetailCollection.add(orderDetailCollectionOrderDetailToAttach);
            }
            orders.setOrderDetailCollection(attachedOrderDetailCollection);
            em.persist(orders);
            if (statusOrderId != null) {
                statusOrderId.getOrdersCollection().add(orders);
                statusOrderId = em.merge(statusOrderId);
            }
            if (restaurantId != null) {
                restaurantId.getOrdersCollection().add(orders);
                restaurantId = em.merge(restaurantId);
            }
            if (paymentMethodId != null) {
                paymentMethodId.getOrdersCollection().add(orders);
                paymentMethodId = em.merge(paymentMethodId);
            }
            if (customerId != null) {
                customerId.getOrdersCollection().add(orders);
                customerId = em.merge(customerId);
            }
            for (OrderDetail orderDetailCollectionOrderDetail : orders.getOrderDetailCollection()) {
                Orders oldOrderIdOfOrderDetailCollectionOrderDetail = orderDetailCollectionOrderDetail.getOrderId();
                orderDetailCollectionOrderDetail.setOrderId(orders);
                orderDetailCollectionOrderDetail = em.merge(orderDetailCollectionOrderDetail);
                if (oldOrderIdOfOrderDetailCollectionOrderDetail != null) {
                    oldOrderIdOfOrderDetailCollectionOrderDetail.getOrderDetailCollection().remove(orderDetailCollectionOrderDetail);
                    oldOrderIdOfOrderDetailCollectionOrderDetail = em.merge(oldOrderIdOfOrderDetailCollectionOrderDetail);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findOrders(orders.getOrderId()) != null) {
                throw new PreexistingEntityException("Orders " + orders + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Orders orders) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Orders persistentOrders = em.find(Orders.class, orders.getOrderId());
            StatusOrder statusOrderIdOld = persistentOrders.getStatusOrderId();
            StatusOrder statusOrderIdNew = orders.getStatusOrderId();
            Restaurant restaurantIdOld = persistentOrders.getRestaurantId();
            Restaurant restaurantIdNew = orders.getRestaurantId();
            PaymentMethod paymentMethodIdOld = persistentOrders.getPaymentMethodId();
            PaymentMethod paymentMethodIdNew = orders.getPaymentMethodId();
            Customer customerIdOld = persistentOrders.getCustomerId();
            Customer customerIdNew = orders.getCustomerId();
            Collection<OrderDetail> orderDetailCollectionOld = persistentOrders.getOrderDetailCollection();
            Collection<OrderDetail> orderDetailCollectionNew = orders.getOrderDetailCollection();
            if (statusOrderIdNew != null) {
                statusOrderIdNew = em.getReference(statusOrderIdNew.getClass(), statusOrderIdNew.getStatusOrderId());
                orders.setStatusOrderId(statusOrderIdNew);
            }
            if (restaurantIdNew != null) {
                restaurantIdNew = em.getReference(restaurantIdNew.getClass(), restaurantIdNew.getRestaurantId());
                orders.setRestaurantId(restaurantIdNew);
            }
            if (paymentMethodIdNew != null) {
                paymentMethodIdNew = em.getReference(paymentMethodIdNew.getClass(), paymentMethodIdNew.getPaymentMethodId());
                orders.setPaymentMethodId(paymentMethodIdNew);
            }
            if (customerIdNew != null) {
                customerIdNew = em.getReference(customerIdNew.getClass(), customerIdNew.getCustomerId());
                orders.setCustomerId(customerIdNew);
            }
            Collection<OrderDetail> attachedOrderDetailCollectionNew = new ArrayList<OrderDetail>();
            for (OrderDetail orderDetailCollectionNewOrderDetailToAttach : orderDetailCollectionNew) {
                orderDetailCollectionNewOrderDetailToAttach = em.getReference(orderDetailCollectionNewOrderDetailToAttach.getClass(), orderDetailCollectionNewOrderDetailToAttach.getOrderDetailId());
                attachedOrderDetailCollectionNew.add(orderDetailCollectionNewOrderDetailToAttach);
            }
            orderDetailCollectionNew = attachedOrderDetailCollectionNew;
            orders.setOrderDetailCollection(orderDetailCollectionNew);
            orders = em.merge(orders);
            if (statusOrderIdOld != null && !statusOrderIdOld.equals(statusOrderIdNew)) {
                statusOrderIdOld.getOrdersCollection().remove(orders);
                statusOrderIdOld = em.merge(statusOrderIdOld);
            }
            if (statusOrderIdNew != null && !statusOrderIdNew.equals(statusOrderIdOld)) {
                statusOrderIdNew.getOrdersCollection().add(orders);
                statusOrderIdNew = em.merge(statusOrderIdNew);
            }
            if (restaurantIdOld != null && !restaurantIdOld.equals(restaurantIdNew)) {
                restaurantIdOld.getOrdersCollection().remove(orders);
                restaurantIdOld = em.merge(restaurantIdOld);
            }
            if (restaurantIdNew != null && !restaurantIdNew.equals(restaurantIdOld)) {
                restaurantIdNew.getOrdersCollection().add(orders);
                restaurantIdNew = em.merge(restaurantIdNew);
            }
            if (paymentMethodIdOld != null && !paymentMethodIdOld.equals(paymentMethodIdNew)) {
                paymentMethodIdOld.getOrdersCollection().remove(orders);
                paymentMethodIdOld = em.merge(paymentMethodIdOld);
            }
            if (paymentMethodIdNew != null && !paymentMethodIdNew.equals(paymentMethodIdOld)) {
                paymentMethodIdNew.getOrdersCollection().add(orders);
                paymentMethodIdNew = em.merge(paymentMethodIdNew);
            }
            if (customerIdOld != null && !customerIdOld.equals(customerIdNew)) {
                customerIdOld.getOrdersCollection().remove(orders);
                customerIdOld = em.merge(customerIdOld);
            }
            if (customerIdNew != null && !customerIdNew.equals(customerIdOld)) {
                customerIdNew.getOrdersCollection().add(orders);
                customerIdNew = em.merge(customerIdNew);
            }
            for (OrderDetail orderDetailCollectionOldOrderDetail : orderDetailCollectionOld) {
                if (!orderDetailCollectionNew.contains(orderDetailCollectionOldOrderDetail)) {
                    orderDetailCollectionOldOrderDetail.setOrderId(null);
                    orderDetailCollectionOldOrderDetail = em.merge(orderDetailCollectionOldOrderDetail);
                }
            }
            for (OrderDetail orderDetailCollectionNewOrderDetail : orderDetailCollectionNew) {
                if (!orderDetailCollectionOld.contains(orderDetailCollectionNewOrderDetail)) {
                    Orders oldOrderIdOfOrderDetailCollectionNewOrderDetail = orderDetailCollectionNewOrderDetail.getOrderId();
                    orderDetailCollectionNewOrderDetail.setOrderId(orders);
                    orderDetailCollectionNewOrderDetail = em.merge(orderDetailCollectionNewOrderDetail);
                    if (oldOrderIdOfOrderDetailCollectionNewOrderDetail != null && !oldOrderIdOfOrderDetailCollectionNewOrderDetail.equals(orders)) {
                        oldOrderIdOfOrderDetailCollectionNewOrderDetail.getOrderDetailCollection().remove(orderDetailCollectionNewOrderDetail);
                        oldOrderIdOfOrderDetailCollectionNewOrderDetail = em.merge(oldOrderIdOfOrderDetailCollectionNewOrderDetail);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = orders.getOrderId();
                if (findOrders(id) == null) {
                    throw new NonexistentEntityException("The orders with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Orders orders;
            try {
                orders = em.getReference(Orders.class, id);
                orders.getOrderId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The orders with id " + id + " no longer exists.", enfe);
            }
            StatusOrder statusOrderId = orders.getStatusOrderId();
            if (statusOrderId != null) {
                statusOrderId.getOrdersCollection().remove(orders);
                statusOrderId = em.merge(statusOrderId);
            }
            Restaurant restaurantId = orders.getRestaurantId();
            if (restaurantId != null) {
                restaurantId.getOrdersCollection().remove(orders);
                restaurantId = em.merge(restaurantId);
            }
            PaymentMethod paymentMethodId = orders.getPaymentMethodId();
            if (paymentMethodId != null) {
                paymentMethodId.getOrdersCollection().remove(orders);
                paymentMethodId = em.merge(paymentMethodId);
            }
            Customer customerId = orders.getCustomerId();
            if (customerId != null) {
                customerId.getOrdersCollection().remove(orders);
                customerId = em.merge(customerId);
            }
            Collection<OrderDetail> orderDetailCollection = orders.getOrderDetailCollection();
            for (OrderDetail orderDetailCollectionOrderDetail : orderDetailCollection) {
                orderDetailCollectionOrderDetail.setOrderId(null);
                orderDetailCollectionOrderDetail = em.merge(orderDetailCollectionOrderDetail);
            }
            em.remove(orders);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Orders> findOrdersEntities() {
        return findOrdersEntities(true, -1, -1);
    }

    public List<Orders> findOrdersEntities(int maxResults, int firstResult) {
        return findOrdersEntities(false, maxResults, firstResult);
    }

    private List<Orders> findOrdersEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Orders.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Orders findOrders(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Orders.class, id);
        } finally {
            em.close();
        }
    }

    public int getOrdersCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Orders> rt = cq.from(Orders.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
